import { defineStore } from 'pinia'
import { store } from '../index'
import { CACHE_KEY, useCache } from '@/hooks/web/useCache'
import { DictApi } from '@/api/system/dict'

export type DictDataType = {
  id: number | undefined
  sort: number | undefined
  label: string
  value: string
  dict_type: string
  status: number
  color_type: string
  css_class: string
  remark: string
  create_time: Date
}

export type DictType = {
  id: number | undefined
  name: string
  type: string
  sort: number | undefined
  status: number
  remark: string
  createTime: Date
}

export interface DictValueType {
  value: any
  label: string
  colorType?: string
  cssClass?: string
}
export interface DictTypeType {
  dictType: string
  dictValue: DictValueType[]
}
export interface DictState {
  dictMap: Map<string, any>
}

export const useDictStore = defineStore('dict', () => {
  const { wsSession } = useCache()
  const dictMap = ref(new Map<string, any>())
  const setDictMap = async () => {
    if (wsSession.getItem(CACHE_KEY.SYSTEM_DICT) && Object.keys(wsSession.getItem(CACHE_KEY.SYSTEM_DICT)).length !== 0) {
      dictMap.value = wsSession.getItem(CACHE_KEY.SYSTEM_DICT)
    } else {
      await initDictType()
    }
  }

  const getDictByType = (type: string) => {
    if (dictMap.value.size === 0) {
      setDictMap()
    }
    return dictMap.value[type]
  }

  const resetDict = async () => {
    wsSession.removeItem(CACHE_KEY.SYSTEM_DICT)
    await initDictType()
  }

  const initDictType = async () => {
    const res = await DictApi.Data.simple()
    // 设置数据
    const dictDataMap = new Map<string, any>()
    res.forEach((dictData: DictDataType) => {
      // 获得 dictType 层级
      const enumValueObj = dictDataMap[dictData.dict_type]
      if (!enumValueObj) {
        dictDataMap[dictData.dict_type] = []
      }
      if (dictData.dict_type === 'infra_config_date_type') {
        console.log({
          value: dictData.value,
          label: dictData.label,
          colorType: dictData.color_type,
          cssClass: dictData.css_class
        })
      }
      // 处理 dictValue 层级
      dictDataMap[dictData.dict_type].push({
        value: dictData.value,
        label: dictData.label,
        colorType: dictData.color_type,
        cssClass: dictData.css_class
      })
    })
    dictMap.value = dictDataMap
    wsSession.setItem(CACHE_KEY.SYSTEM_DICT, dictDataMap) // 60 秒 过期
  }

  return {
    dictMap,
    setDictMap,
    getDictByType,
    resetDict
  }
})

export const useDictStoreWithOut = () => {
  return useDictStore(store)
}
